package com.anxin.act.task.service;

import com.anxin.act.task.dao.WfCcRecordDao;
import com.anxin.act.task.entity.WfCcRecord;
import com.anxin.common.utils.SecurityUtils;
import com.anxin.common.utils.StringUtils;
import com.anxin.framework.web.service.BaseService;
import com.anxin.sys.system.entity.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 流程抄送记录Service业务层处理
 *
 * @author jbs
 * @date 2021-03-30
 */
@Service
public class WfCcRecordService extends BaseService<WfCcRecordDao, WfCcRecord>{
    @Autowired
    private WfCcRecordDao wfCcRecordDao;

    /**
     * 查询流程抄送记录
     *
     * @param id 流程抄送记录ID
     * @return 流程抄送记录
     */
    public WfCcRecord getById(String id){
        return wfCcRecordDao.getById(id);
    }

    /**
     * 查询流程抄送记录列表
     *
     * @param wfCcRecord 流程抄送记录
     * @return 流程抄送记录
     */
    public List<WfCcRecord> findList(WfCcRecord wfCcRecord){
        return wfCcRecordDao.findList(wfCcRecord);
    }

    /**
     * 根据流程
     * @param actId 流程实例ID
     * @return
     */
    public Map<String,StringBuffer> findCcByActId(String actId){
        WfCcRecord wfCcRecord = new WfCcRecord();
        wfCcRecord.setActId(actId);
        List<WfCcRecord> wfCcRecordList = wfCcRecordDao.findList(wfCcRecord);

        Map<String,StringBuffer> resMap = new HashMap();
        for (WfCcRecord ccRecord : wfCcRecordList) {
            StringBuffer userNames = resMap.get(ccRecord.getTaskId());

            if (userNames == null){
                userNames = new StringBuffer();
            }

            StringUtils.bufferAppend(userNames,ccRecord.getUserName(),",");
            resMap.put(ccRecord.getTaskId(),userNames);
        }
        return resMap;
    }

    /**
     * 保存抄送记录
     * @param actId 流程实例Id
     * @param taskId 任务ID
     * @param ccUserList 抄送用户
     */
    @Transactional(readOnly = false)
    public void save(String actId,String taskId,List<String> ccUserList){
        for (String userId : ccUserList) {
            super.save(new WfCcRecord(actId,taskId,userId));
        }
    }

    /**
     * 保存流程抄送记录
     *
     * @param wfCcRecord 流程抄送记录
     * @return 结果
     */
    public int save(WfCcRecord wfCcRecord){
        return super.save(wfCcRecord);
    }


    /**
     * 删除流程抄送记录信息
     *
     * @param id 流程抄送记录ID
     * @return 结果
     */
    public int deleteById(String id){
        SysUser user = SecurityUtils.getUser();
        if(user == null){
            return 0;
        }
        return wfCcRecordDao.deleteById(id,user.getId());
    }
}
